import React, { useEffect, useState } from 'react'
import {
  message, Progress, Radio, Spin, Tabs,
} from 'antd'
import _ from 'lodash'
import { connect } from '@umijs/max'
import moment from 'moment'
import HufuEchartsLine from '@/components/Echarts/line'
import PieCard from './page-components/PieCard'
import styles from './index.less'
import EmptyPic from '@/assets/images/empty.png'

const { TabPane } = Tabs

const execptionLineOptions = {
  xAxis: {
    name: '',
    data: [],
  },
  yAxis: {
    name: '',
  },
  series: [
    {
      data: [],
    },
  ],
}

const GeneralView = (props) => {
  const [activeKey, setActiveKey] = useState(null)
  // const [updateKey, setUpdateKey] = useState(0)
  const [lineOption, setLineOption] = useState(execptionLineOptions)
  const [totalCount, setTotalCount] = useState(0)
  const [appliedCount, setAppliedCount] = useState(0)
  const [totalReqCount, setTotalReqCount] = useState(0)
  const [totalReqErrCount, setTotalReqErrCount] = useState(0)

  const [awaitApprovalCount, setAwaitApprovalCount] = useState(0)
  const [passedApprovalCount, setPassedApprovalCount] = useState(0)
  const [monitorDays, setMonitorDays] = useState(7)

  const [rankingList, setRankingList] = useState([])
  const [rankingTotal, setRankingTotal] = useState(0)
  const [errDistribution, setErrDistribution] = useState([])
  const [rankLoading, setRankLoading] = useState(false)
  const [publishedCount, setPublishedCount] = useState(0)
  const [roleKeys, setRoleKeys] = useState(false)
  const [sign, setSign] = useState(false)

  useEffect(() => {
    queryGetLocalUserAuth()
  }, [])

  useEffect(() => {
    sign && queryGetReqTrendSummary(activeKey)
  }, [monitorDays])

  useEffect(() => {
    sign && initData()
  }, [activeKey])

  // 判断是否显示 全局概览
  const queryGetLocalUserAuth = () => {
    props.dispatch({
      type: 'generalView/queryGetLocalUserAuth',
      cb: (res) => {
        const { msg, data, status } = res
        setRoleKeys(!!data)
        setSign(true)
        if (status === 200) {
          if (data) {
            setActiveKey('0')
          } else {
            setActiveKey('1')
          }
        } else {
          setActiveKey('1')
          message.error(msg || '服务端错误')
        }
      },
    })
  }

  const initData = () => {
    queryGetOverviewSummary(activeKey)
    queryApplyApiById(activeKey)
    queryGetReqTrendSummary(activeKey)
    activeKey === '0' && queryGetTopUserReqSummary() // 调用用户top
    activeKey === '1' && queryGetTopApiReqSummary(activeKey) // 调用量top
    // queryGetTopApiErrReqSummary(activeKey) // 失败次数Top
    queryGetErrDistributionSummary(activeKey) // 错误类型分布统计
  }

  // 头部
  const queryGetOverviewSummary = (type) => {
    props.dispatch({
      type: 'generalView/queryGetOverviewSummary',
      params: {
        type,
      },
      cb: (data) => {
        setTotalCount(data?.totalCount || 0)
        setPublishedCount(data?.publishedCount || 0)
        setAppliedCount(data?.appliedCount || 0)
        setTotalReqCount(data?.totalReqCount || 0)
        setTotalReqErrCount(data?.totalReqErrCount || 0)
      },
    })
  }

  // 申请统计
  const queryApplyApiById = (type) => {
    props.dispatch({
      type: 'generalView/queryGetApprovalSummary',
      params: {
        type,
      },
      cb: (data) => {
        setAwaitApprovalCount(data?.awaitApprovalCount || 0)
        setPassedApprovalCount(data?.passedApprovalCount || 0)
      },
    })
  }

  // 调用次数统计
  const queryGetReqTrendSummary = (type) => {
    props.dispatch({
      type: 'generalView/queryGetReqTrendSummary',
      params: {
        type,
        endDate: moment().format('YYYY-MM-DD'),
        startDate: moment(
          Date.now() - 86400 * 1000 * (monitorDays - 1),
        ).format('YYYY-MM-DD'),
      },
      cb: (res) => {
        const timeArr = []
        const countArr = []
        res?.map(item => {
          timeArr.push(item.time)
          countArr.push(item.count)
          return null
        })
        const copyLineOption = _.cloneDeep(lineOption)
        copyLineOption.xAxis.data = timeArr
        copyLineOption.series = [
          {
            data: countArr,
          },
        ]
        setLineOption(copyLineOption)
      },
    })
  }

  // 调用用户top
  const queryGetTopUserReqSummary = () => {
    setRankLoading(true)
    props.dispatch({
      type: 'generalView/queryGetTopUserReqSummary',
      params: {},
      cb: (res) => {
        const { data, msg, status } = res
        const { list, total } = data || {}
        setRankLoading(false)
        if (status === 200) {
          setRankingList(list)
          setRankingTotal(total)
        } else {
          message.error(msg || '服务端报错')
        }
      },
    })
  }

  // 调用量top
  const queryGetTopApiReqSummary = (type) => {
    setRankLoading(true)
    props.dispatch({
      type: 'generalView/queryGetTopApiReqSummary',
      params: {
        type,
      },
      cb: (res) => {
        const { data, msg, status } = res
        const { list, total } = data || {}
        setRankLoading(false)
        if (status === 200) {
          setRankingList(list)
          setRankingTotal(total)
        } else {
          message.error(msg || '服务端报错')
        }
      },
    })
  }

  // 失败次数Top
  const queryGetTopApiErrReqSummary = (type) => {
    setRankLoading(true)
    props.dispatch({
      type: 'generalView/queryGetTopApiErrReqSummary',
      params: {
        type,
      },
      cb: (res) => {
        const { data, msg, status } = res
        const { list, total } = data || {}
        setRankLoading(false)
        if (status === 200) {
          setRankingList(list)
          setRankingTotal(total)
        } else {
          message.error(msg || '服务端报错')
        }
      },
    })
  }

  // 错误类型分布统计
  const queryGetErrDistributionSummary = (type) => {
    props.dispatch({
      type: 'generalView/queryGetErrDistributionSummary',
      params: {
        type,
      },
      cb: (res) => {
        const { list = [], total } = res || {}
        const resCopy = [...list]
        resCopy.map(item => {
          item.tableRate = item.value / total
          return null
        })
        setErrDistribution(resCopy || [])
      },
    })
  }

  const handlePageTabs = (activeKeyParams) => {
    setActiveKey(activeKeyParams)
    setMonitorDays(7)
  }

  const handleLineTabs = (e) => {
    setMonitorDays(e.target.value)
  }

  const handleBarTabs = (e) => {
    // console.log('handleBarTabs-active', e.target.value)
    const active = e.target.value
    if (active === '1') {
      queryGetTopUserReqSummary()
    }
    if (active === '2') {
      queryGetTopApiReqSummary(activeKey)
    }
    if (active === '3') {
      queryGetTopApiErrReqSummary(activeKey)
    }
  }

  const returnComp = (type) => (
    <>
      <div className={styles.page_content_title}>
        <div className={styles.title_item}>
          <p>{type === '1' ? 'API总数' : '我的发布'}</p>
          <p><span className={styles.num}>{totalCount || publishedCount}</span><span>个</span></p>
          <div className={styles.iconfont_box}>
            <i style={{ fontSize: '.30rem' }} className="iconfont-colour2 icon-API" />
          </div>
        </div>
        <div className={styles.title_item}>
          <p>已申请API</p>
          <p><span className={styles.num}>{appliedCount}</span><span>个</span></p>
          <div className={styles.iconfont_box}>
            <i style={{ fontSize: '.30rem' }} className="iconfont-colour2 icon-shenpi-1" />
          </div>
        </div>
        <div className={styles.title_item}>
          <p>累计调用次数</p>
          <p><span className={styles.num}>{totalReqCount}</span><span>次</span></p>
          <div className={styles.iconfont_box}>
            <i style={{ fontSize: '.30rem' }} className="iconfont-colour2 icon-tiaoyong1" />
          </div>
        </div>
        <div className={styles.title_item}>
          <p>失败次数</p>
          <p><span className={styles.num}>{totalReqErrCount}</span><span>次</span></p>
          <div className={styles.iconfont_box}>
            <i style={{ fontSize: '.30rem' }} className="iconfont-colour2 icon-shibai_1" />
          </div>
        </div>
      </div>
      <div className={styles.page_content_content}>
        <div className={styles.left}>
          <div className={styles.column}>{type === '1' ? '申请统计' : '我的申请'}</div>
          <div className={styles.item}>
            <div className={styles.txt}>
              <span>待审批</span>
              <span className={styles.num}>{awaitApprovalCount}</span>
            </div>
            <div className={styles.iconfont_box}>
              <i className="iconfont-colour2 icon-shijian-1" />
            </div>
          </div>
          <div className={styles.item}>
            <div className={styles.txt}>
              <span>已授权</span>
              <span className={styles.num}>{passedApprovalCount}</span>
            </div>
            <div className={styles.iconfont_box}>
              <i className="iconfont-colour2 icon-shouquan" />
            </div>
          </div>
        </div>
        <div className={styles.right}>
          <div className={styles.column}>
            调用次数统计
            <Radio.Group defaultValue={7} size="small" onChange={handleLineTabs}>
              <Radio.Button value={7}>近7天</Radio.Button>
              <Radio.Button value={30}>近30天</Radio.Button>
            </Radio.Group>
          </div>
          <div className={styles.charts_box}>
            <HufuEchartsLine
              options={lineOption}
            />
          </div>
        </div>
      </div>
      <div className={styles.page_content_footer}>
        <div className={styles.left}>
          <div className={styles.column}>
            调用TOP
            <Radio.Group defaultValue={type === '1' ? '1' : '2'} size="small" onChange={handleBarTabs}>
              {type === '1' && <Radio.Button value="1">调用用户</Radio.Button>}
              <Radio.Button value="2">调用量</Radio.Button>
              <Radio.Button value="3">失败次数</Radio.Button>
            </Radio.Group>
          </div>
          <Spin spinning={rankLoading}>
            {
              rankingList?.length > 0 ? (
                <ul className={styles.ranking_list}>
                  {
                    rankingList?.map(item => (
                      <li className={styles.item} key={item?.rank}>
                        <div className={styles.info}>
                          <div className={styles.info_left}>
                            <span className={styles.no}>{item?.rank}</span>
                            <span className={styles.title} title={item.apiName || item?.username}>{item?.apiName || item?.username}</span>
                          </div>
                          <span className={styles.num}>{item?.totalCount}</span>
                        </div>
                        <Progress strokeColor="#ef5350" percent={(item.totalCount / rankingTotal) * 100} size="small" showInfo={false} strokeLinecap="square" />
                      </li>
                    ))
                  }
                </ul>
              ) : (
                <div className={styles.empty_box}>
                  <img src={EmptyPic} alt="" />
                  <p className={styles.note}>暂无数据</p>
                </div>
              )
            }

          </Spin>
        </div>
        <div className={styles.right}>
          <div className={styles.column}>
            错误类型分布统计
          </div>
          <div className={styles.charts_box}>
            <PieCard data={errDistribution} />
          </div>
        </div>
      </div>
    </>
  )

  return (
    <div className={styles.general_view}>
      <Tabs
        type="card"
        onChange={handlePageTabs}
        activeKey={`${activeKey}`}
        className={styles.page_content_tabs}
      >
        {
          roleKeys && (
            <TabPane tab="全局概览" key="0">{returnComp('1')}</TabPane>
          )
        }

        <TabPane tab="我的概览" key="1">{returnComp('2')}</TabPane>
      </Tabs>
    </div>
  )
}

export default connect(({ generalView }) => ({ ...generalView }))(GeneralView)
